import React, { useMemo, useEffect, useState } from 'react'
import { Navigate, Route, Routes, useLocation, useNavigate } from 'react-router-dom'
import { useSelector } from 'react-redux'
import usePermission, { handleRoles } from '@/permission'
import routes from '@/router'
import Login from '@/pages/login'
import LayoutComponent from '@/components/layout'
import storage from './utils/storage'
import { SELECTED_KEY } from './utils/storage/constant'
import NotFound from './pages/notFound'

const App: React.FC = () => {
  const navigate = useNavigate()
  const { pathname } = useLocation()

  // 为了解决返回登录页，重定向闪屏的问题（方案待优化）
  const [isShow, setIsShow] = useState<boolean>(true)
  const { user } = useSelector(store => (store as IStore)?.user)

  const { userRoutes: authRoutes, userPaths: authPaths } = usePermission()
  const userRoutes = useMemo(() => {
    try {
      // 路由权限配置的错误边界检测
      handleRoles(authRoutes)
    } catch (err) {
      throw `路由信息配置错误, 用户权限子路由roles 应该被包含于父路由roles 中---roles: ${err}`
    }

    return [...routes, ...authRoutes]
  }, [authRoutes])

  const userAllAuthRoutes = useMemo(() => {
    const commonPaths = routes.map(r => r.path)
    return authPaths.concat(commonPaths)
  }, [authPaths])

  const isAuth = useMemo(() => userAllAuthRoutes.includes(pathname), [pathname, userAllAuthRoutes])

  // 没有登录，访问非 '/login' 的页面，重定向到login 页面
  useEffect(() => {
    if (user.code !== 0 && pathname !== '/login') {
      navigate('/login')
      setIsShow(false)
    }
  }, [navigate, pathname, user])

  // 登录了，访问 '/login' 页面，重定向到主页
  useEffect(() => {
    if (user.code === 0 && pathname === '/login') {
      navigate('/')
      setIsShow(true)
    }
  }, [navigate, pathname, user])

  // 初始化访问页面，如果权限被清空了，重定向到login 页面
  useEffect(() => {
    const path = storage.getStorage(SELECTED_KEY)

    if (path) {
      if (user.code === 0) navigate(path)
    } else {
      navigate('/login')
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  return (
    <Routes>
      <Route path='/' element={<Navigate to='/home' />} />
      {
        isAuth ? (
          isShow && <Route path='/*' element={<LayoutComponent routes={userRoutes} />} />
        ) : <Route path='*' element={<NotFound />} />
      }
      <Route path='/login' element={<Login />} />
    </Routes>
  )
}

export default App